﻿using System;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;

/**
 * 
 * @author 失足程序员
 * @Blog http://www.cnblogs.com/shizuchengxuyuan/
 * @mail 492794628@qq.com
 * @phone 13882122019
 */
namespace Net.Sz.Framework.Utils
{

    /// <summary>
    /// 发送邮件
    /// <para>PS:</para>
    /// <para>@author 失足程序员</para>
    /// <para>@Blog http://www.cnblogs.com/shizuchengxuyuan/</para>
    /// <para>@mail 492794628@qq.com</para>
    /// <para>@phone 13882122019</para>
    /// </summary>
    public class MailUtil
    {
        static void Main(string[] args)
        {
            SendMail("smtp.exmail.qq.com", "cf@9599.cn", "深师家园", "cf@9599.cn", "cf@9599.cn", "Cf19871224", "您好！", "这是一封测试邮件!");
            Console.ReadKey();
        }

        /// <summary>
        /// 向用户发送邮件
        /// </summary>
        /// <param name="receiveUser">接收邮件的用户</param>
        /// <param name="sendUser">发送者显求的邮箱地址,可为空</param>
        /// <param name="displayName">收件人显示发件人的联系人名，可为中文</param>
        /// <param name="sendUserName">发送者的邮箱登陆名，可以与发送者地址一样</param>
        /// <param name="userPassword">发送者的登陆密码</param>
        /// <param name="mailTitle">发送标题</param>
        /// <param name="mailContent">发送的内容</param>
        public static void SendMail(string mailHost, string receiveUser, string displayName, string sendUser,
            string sendUserName, string userPassword, string mailTitle, string mailContent)
        {
            MailAddress toMail = new MailAddress(receiveUser);//接收者邮箱
            MailAddress fromMail = new MailAddress(sendUser, displayName);//发送者邮箱       
            MailMessage mail = new MailMessage(fromMail, toMail);
            mail.Subject = mailTitle;
            mail.IsBodyHtml = true;//是否支持HTML
            mail.Body = mailContent;
            SmtpClient client = new SmtpClient();
            client.Host = mailHost;//"smtp.exmail.qq.com";//设置发送者邮箱对应的smtpserver
            client.UseDefaultCredentials = false;
            //client.Port = 465;
            client.Credentials = new NetworkCredential(sendUserName, userPassword);
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            try
            {
                client.Send(mail);
            }
            catch (SmtpException ex)
            {
                Console.Write(ex);
            }
            Console.WriteLine("发送完成");
        }
    }
}
